/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.thoughtbot.expandablecheckrecyclerview.multitypeandcheck;

import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Button;
import ohos.agp.components.Checkbox;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.app.Context;

import com.thoughtbot.expandablecheckrecyclerview.ResourceTable;
import com.thoughtbot.expandablecheckrecyclerview.expand.ExpandFatherItem;
import com.thoughtbot.expandablecheckrecyclerview.expand.ExpandFatherProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * MultiTypeAndCheckContainer
 *
 * @since 2021-07-21
 */
public class MultiTypeAndCheckContainer extends DirectionalLayout {
    private ListContainer listContainer;
    private Component slice;
    private Button cleanButton;

    private List<ExpandFatherItem> fatherData;
    private Map<String, List<MuTypeCheckChildItem>> childData;

    private ExpandFatherItem item;
    private ListContainer childListContainer;
    private ListContainer fatherContainer;
    private ListContainer.ItemClickedListener listener;

    /**
     * MultiTypeAndCheckContainer
     *
     * @param context context
     */
    public MultiTypeAndCheckContainer(Context context) {
        super(context);
    }

    /**
     * MultiTypeAndCheckContainer
     *
     * @param context context
     * @param attrSet attrSet
     */
    public MultiTypeAndCheckContainer(Context context, AttrSet attrSet) {
        super(context, attrSet);
        initView();
    }

    /**
     * MultiTypeAndCheckContainer
     *
     * @param context context
     * @param attrSet attrSet
     * @param styleName styleName
     */
    public MultiTypeAndCheckContainer(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
    }

    private void initView() {
        slice = LayoutScatter.getInstance(getContext()).parse(ResourceTable.Layout_ability_singlecheck_lib, this, true);
        if (slice.findComponentById(ResourceTable.Id_topView) instanceof DirectionalLayout) {
            listContainer = (ListContainer) slice.findComponentById(ResourceTable.Id_listContainer);
            cleanButton = (Button) slice.findComponentById(ResourceTable.Id_clean_button);
        }
    }

    private void initData() {
        ExpandFatherProvider provider = new ExpandFatherProvider(getFatherData(), getContext());
        listContainer.setItemProvider(provider);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer itemListContainer, Component component, int i, long l) {
                fatherContainer = itemListContainer;
                controlExpand(itemListContainer, i);
            }
        });
        listContainer.setLongClickable(false);
        cleanButton.setClickedListener(new ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (fatherContainer != null) {
                    cleanCheck(fatherContainer);
                }
            }
        });

    }

    private void cleanCheck(ListContainer fatherListContainer) {
        int fatherSize = fatherListContainer.getItemProvider().getCount();
        for (int i = 0; i < fatherSize; i++) {
            ExpandFatherItem fatherItem = (ExpandFatherItem) fatherListContainer.getItemProvider().getItem(i);
            childListContainer = fatherItem.getListContainer();
            if (childListContainer == null) {
                continue;
            }
            if (childListContainer.getItemProvider() == null) {
                continue;
            }
            setCheck(childListContainer, false, 1);
        }
    }

    /**
     * 控制折叠和展开
     *
     * @param itemListContainer listContainer
     * @param position position
     */
    private void controlExpand(ListContainer itemListContainer, int position) {
        item = (ExpandFatherItem) itemListContainer.getItemProvider().getItem(position);
        Image imageLabel = item.getImage();
        childListContainer = item.getListContainer();
        if (getListener() == null) {
            childListContainer.setItemClickedListener(new MyListener(item.getListContainer()));
        } else {
            childListContainer.setItemClickedListener(getListener());
        }
        childListContainer.setLongClickable(false);

        // 通过绑定的标签获取到对应的子组件数据
        List<MuTypeCheckChildItem> childItemList = getChildData(item.getTag());
        MultiTypeAndCheckChildProvider childProvider = new MultiTypeAndCheckChildProvider(childItemList, getContext());
        childListContainer.setItemProvider(childProvider);

        // 控制展开或者折叠
        if (!item.isExpand()) {
            childListContainer.setVisibility(Component.VISIBLE);
            item.setExpand(true);
            startAnimation(imageLabel, -180);
        } else {
            childListContainer.setVisibility(Component.HIDE);
            item.setExpand(false);
            startAnimation(imageLabel, 0);
        }
        itemListContainer.getItemProvider().notifyDataChanged();
    }

    /**
     * MyListener
     *
     * @since 2021-07-21
     */
    class MyListener implements ListContainer.ItemClickedListener {

        private ListContainer listContainer;

        public MyListener(ListContainer listContainer) {
            this.listContainer = listContainer;
        }

        @Override
        public void onItemClicked(ListContainer itemListContainer, Component component, int position, long lon) {
            MuTypeCheckChildItem muCheckChildItem = (MuTypeCheckChildItem) listContainer.getItemProvider().getItem(position);
            if (muCheckChildItem != null && !muCheckChildItem.isMark()) {
                return;
            }
            Checkbox checkbox = muCheckChildItem.getCheckbox();
            int size = itemListContainer.getItemProvider().getCount();
            if (!checkbox.isChecked()) {
                checkbox.setChecked(true);
                setCheck(itemListContainer, size, position, false);
            }
        }
    }

    private void setCheck(ListContainer itemChildListContainer, boolean checked, int type) {
        int childSize = itemChildListContainer.getItemProvider().getCount();
        for (int k = 0; k < childSize; k++) {
            MuTypeCheckChildItem muCheckChildItem = (MuTypeCheckChildItem) itemChildListContainer
                .getItemProvider().getItem(k);
            Checkbox checkbox = muCheckChildItem.getCheckbox();
            if (checkbox == null) {
                continue;
            }
            if (type == 1) {
                checkbox.setChecked(checked);
                muCheckChildItem.setChecked(checked);
            } else {
                checkbox.setChecked(muCheckChildItem.isChecked());
            }
        }
    }

    private void setCheck(ListContainer itemListContainer, int size, int position, boolean checked) {
        List<MuTypeCheckChildItem> list = new ArrayList<>();
        String tag = null;
        for (int i = 0; i < size; i++) {
            MuTypeCheckChildItem checkChildItem = (MuTypeCheckChildItem) itemListContainer.getItemProvider().getItem(i);
            if (position == i) {
                checkChildItem.setChecked(true);
                list.add(checkChildItem);
                continue;
            } else {
                Checkbox box = checkChildItem.getCheckbox();
                box.setChecked(checked);
                checkChildItem.setChecked(checked);
            }
            list.add(checkChildItem);
            tag = checkChildItem.getFatherTag();
        }
        childData.put(tag, list);
    }

    /**
     * 单独启动旋转动画
     *
     * @param component component
     * @param rotate rotate
     */
    private void startAnimation(Component component, int rotate) {
        AnimatorProperty animatorProperty = new AnimatorProperty();
        animatorProperty.setTarget(component);
        animatorProperty.rotate(rotate).setDuration(300);
        animatorProperty.setStateChangedListener(new Animator.StateChangedListener() {
            @Override
            public void onStart(Animator animator) {
            }

            @Override
            public void onStop(Animator animator) {
            }

            @Override
            public void onCancel(Animator animator) {
            }

            @Override
            public void onEnd(Animator animator) {

            }

            @Override
            public void onPause(Animator animator) {
            }

            @Override
            public void onResume(Animator animator) {
            }
        });
        animatorProperty.start();
    }

    private List<MuTypeCheckChildItem> getChildData(String fatherTag) {
        return getChildData().get(fatherTag);
    }

    public Map<String, List<MuTypeCheckChildItem>> getChildData() {
        return childData;
    }

    public List<ExpandFatherItem> getFatherData() {
        return fatherData;
    }

    public void setFatherData(List<ExpandFatherItem> fatherData) {
        this.fatherData = fatherData;
    }

    /**
     * setChildData
     *
     * @param childData childData
     */
    public void setChildData(Map<String, List<MuTypeCheckChildItem>> childData) {
        this.childData = childData;
        initData();
    }

    public ListContainer.ItemClickedListener getListener() {
        return listener;
    }

    public void setListener(ListContainer.ItemClickedListener listener) {
        this.listener = listener;
    }
}
